package com.baoyi.pooke;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.util.UUID;

import net.youmi.android.AdManager;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.Toast;

import com.baoyi.content.content;
import com.baoyi.utils.ImageUtil;

public class CamActivity extends Activity {
	static {
		AdManager.init(content.id, content.pwd, content.time, content.con,
				content.banben);
	}
	private boolean isupload = false;
	private ImageView imageView;
	private static final int MESSAGETYPE_01 = 0x0001;
	private ProgressDialog progressDialog = null;
	private Handler handler = new Handler() {
		public void handleMessage(Message message) {
			switch (message.what) {
			case MESSAGETYPE_01:
				// 刷新UI，显示数据，并关闭进度条
				upfile();
				break;
			}
		}
	};
	ImageButton button;
	ImageButton upolad;
	String filename;
	private EditText contentstext;

	// 关闭上传进度条

	private void upfile() {
		progressDialog.dismiss(); // 关闭进度条
		if (isupload) {
			upolad.setVisibility(View.GONE);
			Toast.makeText(CamActivity.this, "上传成功！", Toast.LENGTH_SHORT)
					.show();
			isupload = false;
		} else {
			Toast.makeText(CamActivity.this, "上传失败！", Toast.LENGTH_SHORT)
					.show();
		}
	}

	private String photoPath;
	private String copy;

	// 拍照以后处理结果
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (requestCode == 0 && resultCode == Activity.RESULT_OK) {
			this.imageView.setImageDrawable(Drawable.createFromPath(new File(
					content.pookedir, filename).getAbsolutePath()));
			photoPath = content.pookedir + filename;
			File file = new File(photoPath);
			if (file.exists()) {
				FileInputStream is;
				try {
					is = new FileInputStream(photoPath);
					Bitmap image = BitmapFactory.decodeStream(is);
					is.close();
					image = ImageUtil.zoomBitmap(image,
							MainUI.displayMetrics.widthPixels,
							MainUI.displayMetrics.heightPixels);
					copy = content.locdir + filename;
					File destFile = new File(copy);
					// 创建文件输出流
					OutputStream os = new FileOutputStream(destFile);
					// 存储
					image.compress(CompressFormat.JPEG, 100, os);
					file.delete();
				} catch (FileNotFoundException e1) {
					e1.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				}
				upolad.setVisibility(View.VISIBLE);
			}
		}
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		// Hide the window title.
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.camerasys);
		imageView = (ImageView) this.findViewById(R.id.preview);
		button = (ImageButton) this.findViewById(R.id.cameraButton);
		button.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				pi();
			}

		});
		upolad = (ImageButton) this.findViewById(R.id.cameraupload);
		upolad.setVisibility(View.GONE);
		upolad.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				progressDialog = ProgressDialog.show(CamActivity.this, "上传图片",
						"正在上传图片,请稍候！");
				new Thread() {
					public void run() {
						try {
							File file = new File(copy);
							if (file.exists()) {
								upfiles();
							}

						} catch (Exception e) {
							e.printStackTrace();
							// Toast.makeText(CamActivity.this, "上传失败！",
							// Toast.LENGTH_LONG).show();
						}

						Message msg_listData = new Message();
						msg_listData.what = MESSAGETYPE_01;
						handler.sendMessage(msg_listData);
					}
				}.start();
			}
		});
		contentstext = (EditText) findViewById(R.id.contentstext);
		pi();

	}

	private void pi() {
		Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
		filename = UUID.randomUUID().toString() + ".jpg";
		intent.putExtra(MediaStore.EXTRA_OUTPUT,
				Uri.fromFile(new File(content.pookedir, filename)));
		intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 0);
		startActivityForResult(intent, 0);
	}

	private int timeoutConnection = 14000;
	private int timeoutSocket = 15000;

	/**
	 * 上传文件
	 */
	public void upfiles() {
		HttpParams httpParameters = new BasicHttpParams();// Set the timeout in
															// milliseconds
															// until a
															// connection is
															// established.
															// HttpConnectionParams.setConnectionTimeout(httpParameters,
		// timeoutConnection);// Set the default socket timeout
		// // (SO_TIMEOUT) // in milliseconds which is
		// // the timeout for waiting for data.
		// HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
		HttpClient httpclient = new DefaultHttpClient(httpParameters);
		String urlStr = content.server + "UpFile";
		HttpPost httppost = new HttpPost(urlStr);
		try {
			MultipartEntity entity = new MultipartEntity();

			entity.addPart("macaddress",
					new StringBody(BaoyiApplication.getInstance()
							.getLocalMacAddress(), Charset.forName("UTF-8")));
			String contents = contentstext.getText().toString();
			if (contents == null) {
				contents = "";
			}
			entity.addPart("contents",
					new StringBody(contents, Charset.forName("UTF-8")));
			entity.addPart("fileitem", new FileBody(new File(copy)));
			httppost.setEntity(entity);
			HttpResponse response = httpclient.execute(httppost);
			System.out.println(response.getStatusLine());
			contentstext.setText("");
			isupload = true;
		} catch (UnsupportedEncodingException e) {

		} catch (IOException e) {

		} finally {
			httpclient.getConnectionManager().shutdown();
		}
	}

}
